/**
 * Created by Administrator on 2017/4/18.
 */
/**
 * Created by neal on 11/22/16.
 */
$(".datepicker").datepicker({
    todayBtn: "linked",
    clearBtn: true,
    autoclose: true,
    language: "zh-CN"
});

var CONST_GLOBAL_COMPANY_ID;
var Config = {
    createUrl: '/api/admin/company',
    updateUrl: '/api/admin/company',
    deleteUrl: '/api/company',
    selectUrl: '/api/company',
    updateAuditUrl: '/api/admin/company/audit',
    selectLogisticsNameUrl: '/api/admin/logistics/name',

    createEXUrl: "/api/admin/company/exPrice",

    selectDistrictsUrl: '/api/districts/page',
    selectIndustryUrl:'/api/admin/industry/selectAll',
    selectTypeUrl:'/api/admin/type/selectAll',
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

$("#province").change(function(){
    var id = $(this).val();
    var html = [];
    var selectId = '#city';
    if(id == 1){
        html.push('<option value="'+1+'">'+'北京市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 2){
        html.push('<option value="'+2+'">'+'天津市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 3){
        html.push('<option value="'+3+'">'+'上海市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 4) {
        html.push('<option value="' + 4 + '">' + '重庆市' + '</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else {
        $.ajax({
            url: Config.selectDistrictsUrl,
            data: {parentid:id , page: 1, rows: 1000},
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                getDistrictByParentId(id, "#city");
                $("input[name=districtId]").val(id);

            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error("网络故障");
            }
        });
    }
});
$("#city").change(function(){
    var id = $(this).val();
    $.ajax({
        url: Config.selectDistrictsUrl,
        data: {parentid:id , page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            getDistrictByParentId(id, "#district");
            $("input[name=districtId]").val(id);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
});

$("#industrySelect").change(function () {
    var industryId=$(this).val();
    $.ajax(
        {
            url: "/api/admin/type/selectByIndustry/"+industryId,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">请选择</option>');
                data.data.map(function (type) {
                    categories.push('<option value="');
                    categories.push(type.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(type.name);
                    categories.push('</option>');
                });
                $("#typeSelect").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
});
$("#district").change(function(){
        $("input[name=districtId]").val($(this).val());
});
function getDistrictByParentId(id, selectId) {
    $.ajax({
        url: Config.selectDistrictsUrl,
        data: {parentid:id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var html = [];
            html.push('<option value="" hassubinfo="true">请选择</option>');
            data.data.forEach(function(item){
                html.push('<option value="'+item.id+'">'+item.name+'</option>');
            });
            $(selectId).html(html.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}

$().ready(function () {

    //给行业类型注入值
    $.ajax(
        {
            url: Config.selectIndustryUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">请选择</option>');
                data.data.map(function (industry) {
                    categories.push('<option value="');
                    categories.push(industry.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(industry.name+"("+industry.companyCommission+"%)");
                    categories.push('</option>');
                });
                $("#industrySelect").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    //给商家类型注入值
    // $.ajax(
    //     {
    //         url: Config.selectTypeUrl,
    //         type: "GET",
    //         dataType: "json",
    //         async: false,
    //         success: function (data, textStatus, jqXHR) {
    //             var categories = [];
    //             categories.push('<option value="" hassubinfo="true">请选择</option>');
    //             data.data.map(function (type) {
    //                 categories.push('<option value="');
    //                 categories.push(type.id);
    //                 categories.push('" ');
    //                 categories.push('hassubinfo="true">');
    //                 categories.push(type.name);
    //                 categories.push('</option>');
    //             });
    //             $("#typeSelect").html(categories.join(''));
    //         },
    //         error: function (jqXHR, textStatus, errorThrown) {
    //             toastr.error(errorThrown, textStatus);
    //         }
    //     });
    getDistrictByParentId(0, "#province");
    $.ajax(
        {
            url: Config.selectLogisticsNameUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var logisticsName = [];
                logisticsName.push('<option value=""></option>');
                data.data.map(function (logistics) {
                    logisticsName.push('<option value="');
                    logisticsName.push(logistics.logisticsId);
                    logisticsName.push('" ');
                    logisticsName.push('hassubinfo="true">');
                    logisticsName.push(logistics.name);
                    logisticsName.push('</option>');
                });
                $(".logisticsName").append(logisticsName.join(''));
            }
        });

    $.ajax(
        {
            url: "/api/districts",
            type: "GET",
            data: {parentid: 0, page: 1, rows: 1000},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                if (data && data.data && data.data.length > 0) {
                    var tagsHtml = '';
                    var htagsHtml = '';
                    for (var i = 0; i < data.data.length; i++) {
                        if (data.data[i].id == 7 || data.data[i].id == 26 || data.data[i].id == 31 || data.data[i].id == 32 || data.data[i].id == 33 || data.data[i].id == 34 || data.data[i].id == 35){
                            htagsHtml += '<label><input name="tags" id="tags" type="checkbox" value="' + data.data[i].id + '" />' + data.data[i].name + '</label>    ';
                        }else {
                            tagsHtml += '<label><input name="tags" id="tags" type="checkbox" value="' + data.data[i].id + '" />' + data.data[i].name + '</label>    ';
                        }
                    }
                    $("#cityTags").append(tagsHtml);
                    $("#HcityTags").append(htagsHtml);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });

    $('#buttonGoback').click(function () {
        history.go(-1);
        location.reload();
        return false;
    });
});

var input;
$("input:file").change(function(){
    input = this;
    lrz(this.files[0], {width: 640,quality: 0.75})
        .then(function (rst) {
            // 把处理的好的图片给用户看看呗
            var img = new Image();
            img.src = rst.base64;
            img.onload = function () {
                $(input).siblings("div.update_img").html(img);
            };
            return rst;

        })
        .then(function (rst) {
            // 这里该上传给后端啦
            // 额外添加参数
            rst.formData.append('fileLen', rst.fileLen);
            $.ajax({
                url: '/uploadForCertificate?a='+new Date().getTime(), // 这个地址做了跨域处理，可以用于实际调试
                data: rst.formData,
                enctype: 'multipart/form-data',
                processData: false,
                contentType: false,
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    if(data.type=="SUCCESS"){
                        var id = $(input).attr("id");
                        if (id == "headimgurlFile") {
                            $("#headimgurl").val(data.msg);
                        } else if (id == "imgIdFrontFile") {
                            $("#imgIdFront").val(data.msg);
                        } else if (id == "imgIdBackFile") {
                            $("#imgIdBack").val(data.msg);
                        } else if (id == "imgFrontPhotoFile") {
                            $("#imgFrontPhoto").val(data.msg);
                        } else if (id == "imgOrganizationCodeCertificateFile") {
                            $("#imgOrganizationCodeCertificate").val(data.msg);
                        } else if (id == "xlErCertFile") {
                            $("#xlErCert").val(data.msg);
                        } else if (id == "imgBusinessLicenseFile") {
                            $("#imgBusinessLicense").val(data.msg);
                        }
                        // else if (id == "imgBusinessImgBackFile"){
                        //     $("#businessImgBack").val(data.msg);
                        // } else if (id == "imgHeadPhotoFile"){
                        //     $("#imgHeadPhoto").val(data.msg);
                        // }
                        else {
                            toastr.error("系统错误");
                        }
                        toastr.success("上传成功");
                    }else{
                        toastr.error("上传失败，请稍后重试");
                    }
                }
            });
            return rst;
        })
        .catch(function (err) {
            toastr.error("上传失败，请稍后重试");
        })
        .always(function () {

        });
});

$('input[name=userPhone]').change(function () {
    var phone = $("input[name=userPhone]").val();
    $.ajax({
        url: "/api/admin/company/phone",
        type: "GET",
        data: {phone: phone},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            toastr.success(data.msg, data.title);
            if (data.type != "ERROR"){
                $('input[name=userId]').val(data.data.sysUser);
            }
            var datas = [];
            if (data.type != "ERROR"){
                if(data.data.companies.length != 0){
                    for (var s = 0; s < data.data.companies.length; s++) {
                        console.log(data.data.companies[s]);
                        var dt;
                        switch (data.data.companies[s].companyType) {
                            case 0:
                                dt = "[实体商家]";
                                break;
                            case 1:
                                dt = "[微商]";
                                break;
                            case 2:
                                dt = "[心理咨询]";
                                break;
                            case 3:
                                dt = "[城市合伙人]";
                                break;
                            case 4:
                                dt = "[梦想合伙人]";
                                break;
                            case 8:
                                dt = "[供货商]";
                                break;
                            case 10:
                                dt = "[点餐商家]";
                                break;
                            case 11:
                                dt = "[互动商家(至尊版)]";
                                break;
                            case 12:
                                dt = "[区域代理]";
                                break;
                            case 13:
                                dt = "[互动商家(基础版)]";
                                break;
                        }
                        console.log("dt:" + dt);
                        datas.push(dt);
                    }
                }else {
                    toastr.success("此用户无注册商家");
                }
            }
            console.log(datas);
            $('#company').html("");
            $("#company").html(datas);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });
});
$('#submitCreate').click(function () {
    $("#companyForm").validate();
    if ($('#companyForm').valid()) {
        var msg='';
        // if (!$("#headimgurlFile").val()) {
        //     msg+="公司头像、";
        // }
        // if (!$("#imgIdFrontFile").val()) {
        //     msg+="身份证正面、";
        // }
        // if (!$("#imgIdBackFile").val()) {
        //     msg+="身份证反面、";
        // }
        // if (!$("#imgOrganizationCodeCertificateFile").val()) {
        //     msg+="组织机构代码证、";
        // }
        // if (!$("#xlErCertFile").val()) {
        //     msg+="心理咨询二级证、";
        // }
        // if (!$("#imgBusinessLicenseFile").val()) {
        //
        //     msg+="工商营业执照、";
        // }
        // if(msg!=null||msg!=undefined||msg!=""){
        //     msg=msg.substring(0,msg.length-1);
        //     toastr.error(msg+"不可为空！");
        //     msg="";
        //     return false;
        // }
        //var businessInspectTime =  dateToEpoch($("#businessInspectTime").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessEffectiveTime =  dateToEpoch($("#businessEffectiveTime").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessStartTime =  dateToEpoch($("#businessStartTime").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessEndTime =  dateToEpoch($("#businessEndTime").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
        if (!$("input[name=districtId]").val()){
            toastr.error("请选择地区");
            return false;
        }
        // if (isNaN(businessInspectTime)){
        //     toastr.error("请选择营业许可检查时间");
        //     return false;
        // }
        if (isNaN(businessEffectiveTime)){
            toastr.error("请选择营业许有效时间");
            return false;
        }
        if (isNaN(businessStartTime)){
            toastr.error("请选择营业开始时间");
            return false;
        }
        if (isNaN(businessEndTime)){
            toastr.error("请选择营业结束时间");
            return false;
        }
        //$("#businessInspectTime").val(businessInspectTime);
        $("#businessEffectiveTime").val(businessEffectiveTime);
        $("#businessStartTime").val(businessStartTime);
        $("#businessEndTime").val(businessEndTime);
        $("#provinceIds").val($('#province option:selected').text());
        $("#cityIds").val($('#city option:selected').text());
        $("#districtIds").val($('#district option:selected').text());
        var postData = $('#companyForm').serializeArray();
        $.ajax({
            url: Config.createUrl,
            type: "POST",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data.type ==="ERROR"){
                    toastr.success(data.msg, data.title);
                }else {
                    CONST_GLOBAL_COMPANY_ID = data.data.companyId;
                    toastr.success(data.msg, data.title);
                }
                load();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    }

    return false;
});
$('#submitExCreate').click(function () {
    var logisticsId=$('#logisticsName option:selected').val();
    var price = $('input[name=price]').val() * 100;
    var Ex ="";
    $('input:checkbox[name=tags]:checked').each(function () {
        Ex += $(this).val()+",";
    });
    $('input:checkbox[name=htagsHtml]:checked').each(function () {
        Ex += $(this).val()+",";
    });
    if(Ex==""){
        alert("请选择 地区");
        return false;
    }
    console.log(Ex);
    $.ajax({
        url: Config.createEXUrl,
        type: "POST",
        data: {logisticsId:logisticsId,price: price, provinceId: Ex, companyId: CONST_GLOBAL_COMPANY_ID},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $(":checkbox").attr("checked",false);
            toastr.success(data.msg, data.title);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });
    return false;
});
function isnull(data){
    if(data==null||data==''||data==undefined){
        return false;
    }
    return true;
}

function load() {
    var businessStartTime = new Date($("#businessStartTime").val() * 1).yyyymmddhhmmss();
    var newBusinessStartTime = businessStartTime.substring(0,10);
    var businessEndTime = new Date($("#businessEndTime").val() * 1).yyyymmddhhmmss();
    var newBusinessEndTime = businessEndTime.substring(0,10);
    //var businessInspectTime = new Date($("#businessInspectTime").val() * 1).yyyymmddhhmmss();
    //var newBusinessInspectTime = businessInspectTime.substring(0,10);
    var businessEffectiveTime = new Date($("#businessEffectiveTime").val() * 1).yyyymmddhhmmss();
    var newBusinessEffectiveTime = businessEffectiveTime.substring(0,10);
    $("#businessStartTime").val(newBusinessStartTime);
    $("#businessEndTime").val(newBusinessEndTime);
    //$("#businessInspectTime").val(newBusinessInspectTime);
    $("#businessEffectiveTime").val(newBusinessEffectiveTime);
}





